import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';


//打星
class StarWidget extends StatefulWidget {

  final int max;
  final ValueNotifier<double>? current; //当前多少分
  final double size;
  final double padding;
  final bool canChange;

  const StarWidget(this.max, this.size, this.padding, this.canChange, {Key? key, this.current}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _StarWidgetState();
  }
}

class _StarWidgetState extends BaseState<StarWidget> {

  double? current;

  @override
  void initState() {
    super.initState();


  }

  @override
  Widget build(BuildContext context) {
    current = widget.current?.value;
    print('current: $current');
    if (current != null) {
      int intCurrent = current!.toInt();
      double remainder = current! - intCurrent;
      if (remainder <= 0.2) {
        return buildStar(intCurrent, false);
      } else if (remainder <= 0.7) {
        return buildStar(intCurrent, true);
      } else {
        return buildStar(intCurrent + 1, false);
      }
    } else {
      return buildStar(0, false);
    }
  }

  Widget buildStar(int star, bool halfStar) {
    List<Widget> widgets = [];
    for (int i = 0; i < widget.max; i++) {
      if (i > 0) {
        widgets.add(W(widget.padding));
      }
      if (i < star) {
        if (widget.canChange) {
          widgets.add(InkWell(child: LoadImage('star_18', width: widget.size, height: widget.size), onTap: () { doStar(i); },));
        } else {
          widgets.add(LoadImage('star_18', width: widget.size, height: widget.size));
        }

        continue;
      }
      if (i == star && halfStar) {
        if (widget.canChange) {
          widgets.add(InkWell(child: LoadImage('star_half_18', width: widget.size, height: widget.size), onTap: () { doStar(i); }));
        } else {
          widgets.add(LoadImage('star_half_18', width: widget.size, height: widget.size));
        }
      } else {
        if (widget.canChange) {
          widgets.add(InkWell(child: LoadImage('star_empty_18', width: widget.size, height: widget.size), onTap: () { doStar(i); }));
        } else {
          widgets.add(LoadImage('star_empty_18', width: widget.size, height: widget.size));
        }
      }
    }
    return Row(mainAxisSize: MainAxisSize.min, children: widgets,);
  }

  doStar(int i) {
    print('do star $i');
    current = (i + 1).toDouble();
    widget.current?.value = current!;
    print('do star $i, $current');
    setState(() => null);
  }
}